package com.onpositive.storage.managers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class ProfilesUsersManager {

	public static final String USER_KIND = "UpdateSiteCommitter";

	public static final String NICK_PROP = "NickName";
	public static final String UPDS_PASS_PROP = "Password";

	public static final Map<String,Class> PARAMS_TYPES = new HashMap();
	
	static{
		PARAMS_TYPES.put(NICK_PROP,String.class);
		PARAMS_TYPES.put(UPDS_PASS_PROP,String.class);
	}
	
	private final static DatastoreService dss = DatastoreServiceFactory
			.getDatastoreService();

	public static Map<String, Object> getUsersPref(String nickName) {
		Query q = new Query(USER_KIND);
		q.addFilter(NICK_PROP, FilterOperator.EQUAL, nickName);
		PreparedQuery pq = dss.prepare(q);
		if (pq.countEntities() == 1) {
			Entity e = pq.asSingleEntity();
			return e.getProperties();
		} else {
			return null;
		}
	}

	public static void safeUserProperties(String nickName,
			Map<String, Object> props) {
		Query q = new Query(USER_KIND);
		q.addFilter(NICK_PROP, FilterOperator.EQUAL, nickName);
		PreparedQuery pq = dss.prepare(q);
		if (pq.countEntities() >= 1) {
			List<Key> key = new ArrayList();
			for (Iterator<Entity> i = pq.asIterator(); i.hasNext();) {
				Key k = i.next().getKey();
				key.add(k);
			}
			dss.delete(key);
		}
		Entity e = new Entity(USER_KIND);
		for (String k : props.keySet()) {
			Object val = props.get(k);
			e.setProperty(k, val);
		}
		dss.put(e);
	}

	public static void deleteUserProfile(String nickName) {
		Query q = new Query(USER_KIND);
		q.addFilter(NICK_PROP, FilterOperator.EQUAL, nickName);
		PreparedQuery pq = dss.prepare(q);
		if (pq.countEntities() > 1) {
			List<Key> key = new ArrayList();
			for (Iterator<Entity> i = pq.asIterator(); i.hasNext();) {
				Key k = i.next().getKey();
				key.add(k);
			}
			dss.delete(key);
		}
	}
	
	public static boolean isUserLoginned(String login, String passwd){
		Query q = new Query(USER_KIND);
		q.addFilter(NICK_PROP, FilterOperator.EQUAL, login);
		q.addFilter(UPDS_PASS_PROP, FilterOperator.EQUAL, passwd);
		PreparedQuery pq = dss.prepare(q);
		return pq.countEntities() > 0;
	}
}
